package com.admin.education.dataTransferObject.user.Mapper;

import com.admin.education.common.exceptions.BadRequestException;
import com.admin.education.common.utils.InjectUtil;
import com.admin.education.dataTransferObject.user.Request.BindingInformationRequest;
import com.admin.education.models.*;
import com.admin.education.repositories.ClassRepository;
import com.admin.education.repositories.RoleRepository;
import com.admin.education.repositories.SchoolsRepository;
import com.querydsl.jpa.impl.JPAQuery;
import org.mapstruct.AfterMapping;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;


@Mapper
public abstract class UserMapper {
    @Autowired
    private ClassRepository classRepository;
    @Autowired
    private SchoolsRepository schoolsRepository;
    @Autowired
    private RoleRepository roleRepository;

    public UserMapper() {
        qSchools = QSchools.schools;
        qClasses = QClasses.classes;
        qRole = QRole.role;
    }

    private QSchools qSchools;
    private QClasses qClasses;
    private QRole qRole;

    @Mappings({})
    public abstract UserInformation mapFrom(BindingInformationRequest bindingInformationRequest) throws BadRequestException;

    @AfterMapping
    public void afterMapping(BindingInformationRequest bindingInformationRequest, @MappingTarget UserInformation userInformation) throws BadRequestException {
        if (null != roleRepository) {
            if (0 == this.roleRepository.selectFrom(qRole).where(qRole.id.eq(bindingInformationRequest.getRoleId()), qRole.isValid.eq(true)).fetchCount())
                throw new BadRequestException("角色不存在");
        }
        if (null != schoolsRepository) {
            JPAQuery<Schools> schoolsJPAQuery = this.schoolsRepository.selectFrom(qSchools).where(qSchools.id.eq(bindingInformationRequest.getSchoolId()), qSchools.valid.eq(true));
            if (0 == schoolsJPAQuery.fetchCount())
                throw new BadRequestException("学校不存在");
            else {
                Schools schools = schoolsJPAQuery.fetchOne();
                if (0 == schools.getClasses().stream().filter(p -> p.getId() == bindingInformationRequest.getClassId() && p.isValid()).count())
                    throw new BadRequestException("班级不存在");
            }
        }

        userInformation.setClasses(this.classRepository.selectFrom(qClasses).where(qClasses.id.eq(bindingInformationRequest.getClassId())).fetchOne());
        userInformation.setSchools(this.schoolsRepository.selectFrom(qSchools).where(qSchools.id.eq(bindingInformationRequest.getSchoolId())).fetchOne());
        userInformation.setRoles(this.roleRepository.selectFrom(qRole).where(qRole.id.eq(bindingInformationRequest.getRoleId())).fetchOne());
    }
}
